package com.example.finaltest.shoppingCart;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;

import com.example.finaltest.R;
import com.example.finaltest.goods.PaymentActivity;
import com.example.finaltest.utils.BaseActivity;
import com.example.finaltest.utils.UtilTool;
import com.example.finaltest.utils.UtilsLog;

import java.util.ArrayList;
import java.util.List;

import in.srain.cube.views.ptr.PtrClassicDefaultHeader;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;

import static in.srain.cube.views.ptr.util.PtrLocalDisplay.dp2px;


public class shoppingCartActivity extends BaseActivity implements  ShoppingCartAdapter.CheckInterface, ShoppingCartAdapter.ModifyCountInterface{
    ListView listView;
    CheckBox allCheckBox;
    TextView totalPrice,goPay;
    ImageView back;
    LinearLayout orderInfo,empty_shopcart,shareInfo,llCart;
    PtrFrameLayout mPtrFrame;
    Button actionBarEdit;
    Goods goodsBean;
    private Context mcontext;
    private double mtotalPrice = 0.00;
    private int mtotalCount = 0;
    private ShoppingCartAdapter adapter;
    private List<Goods.GoodsInfo> childs; //子元素的列表

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.shopping);
        goodsBean= (Goods)getIntent().getSerializableExtra("data");
        initView();
        initPtrFrame();
        initData();
        initEvents();
        setListener();

    }



    private void initView() {
        listView = findViewById(R.id.listView);
        allCheckBox = findViewById(R.id.all_checkBox);
        totalPrice = findViewById(R.id.total_price);
        goPay = findViewById(R.id.go_pay);
        orderInfo= findViewById(R.id.order_info);
        shareInfo = findViewById(R.id.share_info);
        llCart =findViewById(R.id.ll_cart);
        mPtrFrame = findViewById(R.id.mPtrframe);
        back = findViewById(R.id.shopping_back);
        empty_shopcart = findViewById(R.id.layout_empty_shopcart);
    }

    private void initPtrFrame() {
        final PtrClassicDefaultHeader header=new PtrClassicDefaultHeader(this);
        header.setPadding(dp2px(20), dp2px(20), 0, 0);
        mPtrFrame.setHeaderView(header);
        mPtrFrame.addPtrUIHandler(header);
        mPtrFrame.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                mPtrFrame.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mPtrFrame.refreshComplete();
                    }
                },2000);
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header);
            }
        });
    }

    private void setListener() {
        allCheckBox.setOnClickListener(listener);
        goPay.setOnClickListener(listener);
        back.setOnClickListener(listener);
    }

    View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            AlertDialog dialog;
            switch (view.getId()) {
                case R.id.all_checkBox:
                    doCheckAll();
                    break;
                case R.id.shopping_back:
                    finish();
                    break;
                case R.id.go_pay:
                    if (mtotalCount == 0) {
                        UtilTool.toast(mcontext, "请选择要支付的商品");
                        return;
                    }
                    Goods goodsBean1 = goodsBean;
                    List<Goods.GoodsInfo> ls = new ArrayList<>();
                    for(Goods.GoodsInfo t:childs){
                        if(t.isChoosed()){
                            ls.add(t);
                        }
                    }
                    goodsBean1.setData(ls);
                    Intent intent = new Intent(mcontext, PaymentActivity.class);
                    intent.putExtra("toflg",2);
                    intent.putExtra("goods",goodsBean1);
                    startActivity(intent);
                    finish();
                    break;
            }
        }
    };

    private void initData() {
        mcontext = this;
        childs = new ArrayList<>();
        List<Goods.GoodsInfo> list = goodsBean.getData();
        childs.addAll(list);
        //adapter.notifyDataSetChanged();
    }

    private void initEvents() {
        adapter = new ShoppingCartAdapter(childs,this,0);
        adapter.setCheckInterface(this);//关键步骤1：设置复选框的接口
        adapter.setModifyCountInterface(this); //关键步骤2:设置增删减的接口
        listView.setAdapter(adapter);
        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                int firstVisiablePostion=view.getFirstVisiblePosition();
                int top=-1;
                View firstView=view.getChildAt(firstVisibleItem);
                UtilsLog.i("childCount="+view.getChildCount());//返回的是显示层面上的所包含的子view的个数
                if(firstView!=null){
                    top=firstView.getTop();
                }
                UtilsLog.i("firstVisiableItem="+firstVisibleItem+",fistVisiablePosition="+firstVisiablePostion+",firstView="+firstView+",top="+top);
                if(firstVisibleItem==0&&top==0){
                    mPtrFrame.setEnabled(true);
                }else{
                    mPtrFrame.setEnabled(false);
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        setCartNum();
    }

    private void setCartNum() {
        //购物车已经清空
        int count = 0;
        for(int i=0;i<childs.size();i++)
        {
            childs.get(i).setChoosed(allCheckBox.isChecked());
            count++;
        }
        if (count == 0 ) {
            clearCart();
        }

    }
    private void clearCart() {
        actionBarEdit.setVisibility(View.GONE);
        llCart.setVisibility(View.GONE);
        empty_shopcart.setVisibility(View.VISIBLE);//这里发生过错误
    }


    public void checkChild(int childPosition, boolean isChecked) {
        if (isCheckAll()) {
            allCheckBox.setChecked(true);//全选
        } else {
            allCheckBox.setChecked(false);//反选
        }

        adapter.notifyDataSetChanged();
        calulate();

    }

    private boolean isCheckAll() {
        for(int i=0;i<childs.size();i++)
        {
            if(!childs.get(i).isChoosed()){
                return false;
            }
        }
        return true;
    }

    private void doCheckAll() {
        for (int j = 0; j < childs.size(); j++) {
            childs.get(j).setChoosed(allCheckBox.isChecked());//这里出现过错误
        }
        adapter.notifyDataSetChanged();
        calulate();
    }


    public void doUpdate(int childPosition, View showCountView) {
        Goods.GoodsInfo good = (Goods.GoodsInfo) adapter.getItem(childPosition);
        int count = good.getCount();
        UtilsLog.i("进行更新数据，数量" + count + "");
        ((TextView) showCountView).setText(String.valueOf(count));
        adapter.notifyDataSetChanged();
        calulate();


    }


    private void calulate() {
        mtotalPrice = 0.00;
        mtotalCount = 0;
        for (int j = 0; j < childs.size(); j++) {
            Goods.GoodsInfo good = childs.get(j);
            if (good.isChoosed()) {
                mtotalCount++;
                mtotalPrice += good.getUnivalence()* good.getCount();
            }
        }
        totalPrice.setText("￥" + mtotalPrice + "");
        goPay.setText("去支付(" + mtotalCount + ")");
        if (mtotalCount == 0) {
            setCartNum( );
        }


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        adapter = null;
        childs.clear();
        mtotalPrice = 0.00;
        mtotalCount = 0;
    }

}
